package appapi.service.impl;

import appapi.Global.BusinessException;
import appapi.Request.EquiPageReq;
import appapi.Request.InspectionPageReq;
import appapi.Vo.OnsitPageVo;
import appapi.Vo.record.InspectWarnVo;
import appapi.Vo.record.OnSiteDetailVo;
import appapi.Vo.record.OnSiteRecVo;
import appapi.dao.*;
import appapi.dto.AnnexType;
import appapi.dto.OnsiteRecModel;
import appapi.entity.Zhongjiao.AnnexDto;
import appapi.entity.Zhongjiao.OnsitedetailDto;
import appapi.entity.Zhongjiao.OnsiteinspectionDto;
import appapi.entity.app.AnnexEntity;
import appapi.entity.app.OnsitedetailEntity;
import appapi.entity.app.RectificationEntity;
import appapi.entity.basic.UserInfo;
import appapi.service.IOnsiteinspectionService;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author djq
 * @date 2023/5/20 9:06
 * @description:
 */
@Component
public class OnsiteinspectionServiceImpl implements IOnsiteinspectionService {
    @Resource
    private OnsiteinspectionMapper onsiteinspectionMapper;
    @Resource
    private OnsitedetailMapper onsitedetailMapper;
    @Resource
    private RectificationMapper rectificationMapper;
    @Resource
    StaffMapper staffMapper;
    @Resource
    AnnexMapper annexMapper;
    @Resource
    EquipmentMapper equipmentMapper;

    @Override
    public List<OnsitPageVo> SelectInspectionPage(InspectionPageReq req) {

        PageHelper.startPage(req.getCurrPage(), req.getPageSize());
        return onsiteinspectionMapper.selectInspectionPage(req);
    }

    @Override
    public List<Map<String, Object>> SelectInspectionList(Long equipId) {
        return onsiteinspectionMapper.selectInspectionList(equipId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void InsertInspection(OnSiteRecVo vo) {
        //新增记录
        OnsiteinspectionDto dto = vo.vo2Entity();
        dto.setCreateTime(LocalDateTime.now());
        dto.setUpdateTime(LocalDateTime.now());
        int iRet = onsiteinspectionMapper.insertSelective(dto);
        if (iRet <= 0) {
            throw new BusinessException(500, "新增记录失败!");
        }
        Long onsiteId = dto.getOnsitId();
        //添加巡检明细
        AddDetail(onsiteId, vo.getDetails());
        //是否存在整改
        List<String> expList = vo.getDetails().stream()
                .filter(OnSiteDetailVo -> OnSiteDetailVo.getOnsiteResult() == 1)
                .map(OnSiteDetailVo::getOnsiteItem)
                .collect(Collectors.toList());
        if (expList.size() > 0) {
            //异常，添加整改信息
            List<RectificationEntity> rectList = new ArrayList<>();
            RectificationEntity rectEntity = new RectificationEntity();
            rectEntity.setRectItem(String.join(",", expList));
            rectEntity.setRectRequire(vo.getExpRequire());
            rectEntity.setEquipId(vo.getEquipId());
            rectEntity.setRectState(0);
            rectEntity.setRectAdd(1);
            rectEntity.setRectSource(onsiteId);
            rectEntity.setRectType(AnnexType.AnnexTypeEnum.onsiteInspection.getCode());
            rectEntity.setSoutOper(vo.getOperator());
            rectEntity.setRectDate(new Date());
            rectEntity.setCreateTime(LocalDateTime.now());
            rectEntity.setUpdateTime(LocalDateTime.now());
            rectList.add(rectEntity);
            rectificationMapper.insertBatch(rectList);
        }
        //由附件则新增附件
        if (dto.getAnnexUrl() != null && dto.getAnnexUrl().size() > 0) {
            List<AnnexEntity> annexCollect = dto.getAnnexUrl().stream().map(annex -> {
                AnnexEntity entity = new AnnexEntity();
                entity.setCreateTime(LocalDateTime.now());
                entity.setUpdateTime(LocalDateTime.now());
                entity.setAnnexTitle("巡检");
                entity.setAnnexType(AnnexType.AnnexTypeEnum.onsiteInspection.name());
                entity.setAnnexUrl(annex);
                entity.setCreateUser(vo.getCreateUser());
                entity.setRecId(onsiteId);
                return entity;
            }).collect(Collectors.toList());

            annexMapper.insertList(annexCollect);
        }
    }

    /**
     * 添加巡检明细
     *
     * @param onsiteId
     * @param detailVos
     */
    private void AddDetail(Long onsiteId, List<OnSiteDetailVo> detailVos) {
        List<OnsitedetailEntity> entityList = new ArrayList<>();
        for (OnSiteDetailVo vo : detailVos
        ) {
            OnsitedetailEntity entity = vo.vo2Entity();
            entity.setOnsiteId(onsiteId);
            entity.setAuditState(0);
            entity.setCreateTime(LocalDateTime.now());
            entity.setUpdateTime(LocalDateTime.now());
            entity.setImgUrl(String.join(",", vo.getImgUrlList()));
            entityList.add(entity);
        }
        if (entityList.size() > 0) {
            onsitedetailMapper.insertList(entityList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void UpdateInspection(OnSiteRecVo vo) {
        OnsiteinspectionDto dto = vo.vo2Entity();
        dto.setUpdateTime(LocalDateTime.now());
        if (onsiteinspectionMapper.updateByPrimaryKeySelective(dto) == 0) {
            throw new BusinessException(500, "更新失败");
        } else {
            Long onsiteId = vo.getOnsitId();
            //1.删除巡检详情
            onsitedetailMapper.deleteByOnsiteId(dto.getOnsitId());
            //2.删除整改信息
            rectificationMapper.deleteByRecId(AnnexType.AnnexTypeEnum.onsiteInspection.getCode(), onsiteId);
            //3.重新写入巡检详情
            AddDetail(onsiteId, vo.getDetails());
            //4.是否存在整改信息
            List<String> expList = vo.getDetails().stream()
                    .filter(OnSiteDetailVo -> OnSiteDetailVo.getOnsiteResult() == 1)
                    .map(OnSiteDetailVo::getOnsiteItem)
                    .collect(Collectors.toList());
            if (expList.size() > 0) {
                //异常，添加整改信息
                List<RectificationEntity> rectList = new ArrayList<>();
                RectificationEntity rectEntity = new RectificationEntity();
                rectEntity.setRectItem(String.join(",", expList));
                rectEntity.setRectRequire(vo.getExpRequire());
                rectEntity.setEquipId(vo.getEquipId());
                rectEntity.setRectState(0);
                rectEntity.setRectAdd(1);
                rectEntity.setRectSource(onsiteId);
                rectEntity.setRectType(AnnexType.AnnexTypeEnum.onsiteInspection.getCode());
                rectEntity.setSoutOper(vo.getOperator());
                rectEntity.setRectDate(new Date());
                rectEntity.setCreateTime(LocalDateTime.now());
                rectEntity.setUpdateTime(LocalDateTime.now());
                rectList.add(rectEntity);
                rectificationMapper.insertBatch(rectList);
            }
            annexMapper.deleteByRecId(AnnexType.AnnexTypeEnum.onsiteInspection.name(), Collections.singletonList(onsiteId));
            //5.附件则新增附件
            if (dto.getAnnexUrl().size() > 0) {
                List<AnnexEntity> annexCollect = dto.getAnnexUrl().stream().map(annex -> {
                    AnnexEntity entity = new AnnexEntity();
                    entity.setCreateTime(LocalDateTime.now());
                    entity.setUpdateTime(LocalDateTime.now());
                    entity.setAnnexTitle("巡检");
                    entity.setAnnexType(AnnexType.AnnexTypeEnum.onsiteInspection.name());
                    entity.setAnnexUrl(annex);
                    entity.setCreateUser(vo.getCreateUser());
                    entity.setRecId(onsiteId);
                    return entity;
                }).collect(Collectors.toList());
                annexMapper.insertList(annexCollect);
            }
        }
    }


    @Override
    public void DelInspection(List<Long> onsitIds) {
        int iRet = onsiteinspectionMapper.deleteByIds(onsitIds);
        if (iRet > 0) {
            //删除明细
            onsitedetailMapper.deleteByOnsiteIds(onsitIds);
            //删除整改信息
            rectificationMapper.deleteSourcesBatch(AnnexType.AnnexTypeEnum.onsiteInspection.getCode(), onsitIds);
        }
    }

    @Override
    public OnsiteRecModel getDetail(Long onsitId) {
        OnsiteRecModel recModel = onsiteinspectionMapper.selectModel(onsitId);
        if (recModel != null) {
            //获取巡检详情
            List<OnsitedetailDto> details = onsitedetailMapper.selectByOnsiteId(onsitId);
            recModel.setDetail(details);
            List<AnnexDto> annexDtos = annexMapper.selectAllByRecId(AnnexType.AnnexTypeEnum.onsiteInspection.name(), onsitId);

            recModel.setAnnexUrl(annexDtos.stream().map(AnnexDto::getAnnexUrl).collect(Collectors.toList()));

        }
        return recModel;
    }

    @Override
    public InspectWarnVo GetWarn(UserInfo userInfo) {
        InspectWarnVo vo = new InspectWarnVo();
        //拿到该人员的信息
        Map<String, Object> staffInfo = staffMapper.selectStaffDetail(userInfo.getUserid());
        EquiPageReq req = new EquiPageReq();
        req.setOrgaPathIds(staffInfo.get("orgaPathIds").toString());
        //查到该人员能看到的所有设备
        List<Map<String, Object>> list = equipmentMapper.selectEquiPageList(req);

        List<Long> equipIds = list.stream().map(map -> (Long) map.get("equipId")).collect(Collectors.toList());

        //拿到本月进行过巡检的数据
        List<Map<String, Object>> monthInfos = onsiteinspectionMapper.selectListByMonth(equipIds);

        vo.setEquipNum(list.size());
        vo.setCheckNum(monthInfos.size());
        vo.setNotCheckNum(vo.getEquipNum() - vo.getCheckNum());
        return vo;
    }

    @Override
    public List<OnsitPageVo> getList(InspectionPageReq req) {
        return onsiteinspectionMapper.selectInspectionPage(req);
    }



}
